var time = 0;
var _CK_ = null;
var bOpen = 0;
var bObj = null;
var msgcache = {};
var player;
var url_list;
var currentUrl;
var nextid;
var video_urls = [];
var cut_mode=0;	// 0正常播放模式，1切割模式
function BrowserType() {
	var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串 
	var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器 
	// var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器 
	var isIE = window.ActiveXObject || "ActiveXObject" in window
	// var isEdge = userAgent.indexOf("Windows NT 6.1; Trident/7.0;") > -1 && !isIE; //判断是否IE的Edge浏览器 
	var isEdge = userAgent.indexOf("Edge") > -1; //判断是否IE的Edge浏览器
	var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器 
	var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器 
	var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1 && !isEdge; //判断Chrome浏览器 

	if (isIE) {
		var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
		reIE.test(userAgent);
		var fIEVersion = parseFloat(RegExp["$1"]);
		if (userAgent.indexOf('MSIE 6.0') != -1) {
			return "IE6";
		} else if (fIEVersion == 7) { return "IE7"; }
		else if (fIEVersion == 8) { return "IE8"; }
		else if (fIEVersion == 9) { return "IE9"; }
		else if (fIEVersion == 10) { return "IE10"; }
		else if (userAgent.toLowerCase().match(/rv:([\d.]+)\) like gecko/)) {
			return "IE11";
		}
		else { return "0" }//IE版本过低
	}//isIE end 
	if (isFF) { return "FF"; }
	if (isOpera) { return "Opera"; }
	if (isSafari) { return "Safari"; }
	if (isChrome) { return "Chrome"; }
	if (isEdge) { return "Edge"; }
}//myBrowser() end 
function SetCookie(name, value) {
	var Days = 30;
	var exp = new Date();
	exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
function getCookie(name) {
	var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
	if (arr != null) return unescape(arr[2]); return null;
}
window.onerror = function () {
	return true;
}
function setMovieColor(url,index=1,all_index=1){
	var videolist = $('.videolist').children();
	// var videolist = document.getElementById('videolist');
	for(var i=0; i<videolist.length; i++){
		var obj = videolist[i];
		// console.log($(obj).attr('url'));
		if(url==$(obj).attr('url').trim()){
			$(obj).css({"color":"#2f58ee"});
		}else{
			$(obj).css({"color":"aqua"});
		}
	};
	document.getElementById('mvideo').innerText = 'aa';
	// console.log($('span[name$="del"]'));
	// $('span[name$="del"]').attr('currenturl',url);
	// $(obj).css({"color","#2f58ee"});
}
function play(){
	player.play();
}
function pause(){
	if(player.paused){
		player.play();
	}else{
		player.pause();
	}
}
function getprogress(){
	var t = player.video.currentTime;
	return t;
}
function switchMovie(url){
	// console.log("下一个视频："+url);
	var urlindex = url_list.indexOf(currentUrl);
	if(url==''){
		if (urlindex<url_list.length-1){
			url = url_list[urlindex+1];
			console.log('下一个视频：'+url);
		}else{
			var url = "/play/"+nextid;
			window.location.href=url;
		}
	}else if(url=='pre'){
		if (urlindex>0){
			url = url_list[urlindex-1];
		}else{
			url = url_list[url_list.length-1];
		}
	}else if(url=='next'){
		if (urlindex<url_list.length-1){
			url = url_list[urlindex+1];
		}else{
			url = url_list[0];
		}
	}
	player.switchVideo(
	{
		url:url,
	});
	player.play();
	currentUrl = url;
	$('span[name$="del"]').attr('currenturl',currentUrl);
	setMovieColor(currentUrl);
}
function to_cut_mode(n){
	cut_mode=n;
}
function play_to(t){
	player.seek(t);
}
function volume_to(t){
	var volume = player.volume();
	volume += t;
	if(volume<0){
		volume=0;
	}
	if(volume>1){
		volume=1;
	}
	player.volume(volume);
}

function timeHandler(t) {
	if (t > -1)
		SetCookie(videoid + "_time", t);
}
function loadHandler() {
	player.addListener('time', timeHandler); //监听播放时间
}
function init() {
	var cookieTime = getCookie(videoid + "_time"); //调用已记录的time
	//alert("上次播放时间"+ cookieTime +"");
	if (!cookieTime || cookieTime == undefined) { //如果没有记录值，则设置时间0开始播放
		cookieTime = 0;
	}
	if (playertype == 'ckplayer')
		ckplay(box,main, xml, videoid, urls, pic, cookieTime);
	else
		dplay(box,main,nextid,area, videoid, urls, cookieTime);
}
//ckplayer
function ckplay(box,main, xml, videoid, urls, pic, starttime) {
	
	var hostname = window.location.hostname
	
	var port = window.location.port || '80';
	var picurl = window.location.protocol + "//" + window.location.host + pic;
	
	var url = main;	
	
	xml = window.location.protocol + "//" + window.location.host + xml
	var videoObject = null;
	var isiPad = navigator.userAgent.match(/iPhone|Linux|Android|iPad|iPod|ios|iOS|Windows Phone|Phone|WebOS/i) != null;
	
	if (isiPad) {
		document.getElementById('mvideo').innerHTML = '<video src="' + url + '" poster="' + picurl + '" controls="controls" webkit-playsinline="true" style="width: 100%; height: 100%; background-color: rgb(0, 0, 0);" width="100%" height="100%"></video>'
	}else
	{
		//ck参数
		var l = ''
		var r = ''
		var t = ''
		var d = ''
		var u = ''
		videoObject = {
			container: '.video',
			variable: 'player',
			loaded: 'loadHandler',
			autoplay: true,
			poster: picurl,
			adfront: l, //前置广告
			adfronttime: t,
			adfrontlink: r,
			adpause: d,//暂停广告
			adpausetime: t,
			adpauselink: u,
			video: url
		};
	}

	
	

	if (starttime > 0) {
		videoObject['seek'] = starttime;
	}
	
	player = new ckplayer(videoObject);


}

//获得多码率列表
function getPlayList(url, cb) {
	$.get(url, function (result) {
		cb(null, result);
	})
}

function newplayer(box,main, urls){
	// getPlayList(main, function (err, result) {
		var url = main
		var url_list = urls.trim().split(" ")
		var playcfg = {
			container: document.getElementById(box),
			screenshot: true,
			pic: pic,
			video: {
				url: url,
				type: "hls"
			}
		};
		currentUrl = url;
		//多码率
		// if (result) {
		// 	var labels = ["标清","高清","超清","蓝光"]
		// 	var parser = new m3u8Parser.Parser();
		// 	parser.push(result);
		// 	parser.end();
		// 	var qualitys = [];
		// 	var playlist = parser.manifest.playlists;
		// 	if (playlist && playlist.length > 1) {
		// 		// console.log(playlist)
		// 		for (var i = 0; i < playlist.length; i++) {
		// 			qualitys.push({
		// 				name: labels[i],
		// 				url:  playlist[i].uri,
		// 				type: 'hls'
		// 			})
		// 		}
		// 		playcfg.video.quality = qualitys
		// 		delete playcfg.video.url;
		// 		playcfg.video.defaultQuality = 0;
		// 	}
		// }
		var newplayer = new DPlayer(playcfg); 	// player为全局变量
		newplayer.on('ended',function(){
			var urlindex = url_list.indexOf(currentUrl);
			if (urlindex<url_list.length-1){
				url = url_list[urlindex+1];
				console.log('下一个视频：'+url);
				newplayer.switchVideo(
				{
					url:url,
				});
				newplayer.play();
				currentUrl = url;
				setMovieColor(currentUrl,index=urlindex+1,all_index=url_list.length);
			}else{
				var url = "/play/"+nextid;
				window.location.href=url;
			}
		})
		newplayer.play();
		setMovieColor(currentUrl);
	// }
}
//dplayer
function dplay(box,main,nextid,area, videoid, urls,  starttime) {
	// console.log(box);
	getPlayList(main, function (err, result) {
		var url = main
		nextid = nextid
		url_list = urls
		var playcfg = {
			container: document.getElementById(box),
			screenshot: true,
			pic: pic,
			video: {
				url: url,
				type: "hls"
			},
			contextmenu:[
				{
					text:'set video logo',
					click:(player) => {
						$('#logo').click();
					}
				}
			]
		};
		currentUrl = url;
		//多码率
		if (result) {
			var labels = ["标清","高清","超清","蓝光"]
			var parser = new m3u8Parser.Parser();
			parser.push(result);
			parser.end();
			var qualitys = [];
			var playlist = parser.manifest.playlists;
			if (playlist && playlist.length > 1) {
				// console.log(playlist)
				for (var i = 0; i < playlist.length; i++) {
					qualitys.push({
						name: labels[i],
						url:  playlist[i].uri,
						type: 'hls'
					})
				}
				playcfg.video.quality = qualitys
				delete playcfg.video.url;
				playcfg.video.defaultQuality = 0;
			}
		}

		player = new DPlayer(playcfg); 	// player为全局变量
		// 记录上次播放位置
		// if(videoid){
		// 	player.on('timeupdate', function () {

		// 		var t = player.video.currentTime;
		// 		if (t > 0)
		// 			SetCookie(videoid + "_time", t);
		// 	})
		// }
		// 绑定拖动等事件
		if(videoid){
			console.log("绑定事件");
			player.on('ended',function(){
				var urlindex = url_list.indexOf(currentUrl);
				if (urlindex<url_list.length-1){	// 切换下个片段
					url = url_list[urlindex+1];
					console.log('下一个片段：'+url);
					player.switchVideo(
					{
						url:url,
					});
					player.play();
					currentUrl = url;
					setMovieColor(currentUrl,index=urlindex+1,all_index=url_list.length);
				}else{		// 切换下个电影
					if(cut_mode==0){
						;	//播放完后，手动切到下一个电影
						// var url = "/play/"+nextid;
						// window.location.href=url;
					}
				}
			});
			// player.on('play',function(){
			// 	console.log('play')
			// });
			// player.on('pause',function(){
			// 	console.log('pause')
			// })
			//player.on('mousemove',function(){
			//	console.log('onmousemove');
			//	palyer.play()
			//});
			// player.video.onprogress = function(){
			// 	var t = player.video.currentTime;
			// 	var H = (Array(2).join("0") + Math.floor(t/3600)).slice(-2)
			// 	var M = (Array(2).join("0") + Math.floor((t%3600)/60)).slice(-2)
			// 	var S = (Array(2).join("0") + parseInt((t%3600)%60)).slice(-2)
			// 	var value = H+":"+M+":"+S
			// 	$("#currentTime").attr('value',value);
			// }
			// player.video.onmouseout = function(){
			//	 //debugger
			//	 $('.dplayer-bar').focus();
			// 	console.log('onmouseout')
			// };
			// player.video.onseeked = function(){
			// 	var t = player.video.currentTime;
			// 	console.log(t);
			// }
			// player.video.onseeked = function(){
			// 	var t = player.video.currentTime;
			// }
			// player.video.onpause = function(){
			// 	var t = player.video.currentTime;
			// 	console.log(t);
			// }
		}



		if (starttime > 0)
			player.seek(starttime)

		player.play();
		setMovieColor(currentUrl);
	})
}